package com.moxing.admin.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.NetworkInterface;


@Slf4j
@Component
public class IdWorkUtil {
    // 起始的时间戳（可设置当前时间之前的某个时间点）
    private final static long START_TIMESTAMP = 1640995200000L; // 2022-01-01 00:00:00

    // 每一部分占用的位数
    private final static long SEQUENCE_BIT = 12; // 序列号占用的位数
    private final static long MACHINE_BIT = 5;   // 机器标识占用的位数
    private final static long DATACENTER_BIT = 5;// 数据中心占用的位数

    // 每一部分的最大值
    private final static long MAX_DATACENTER_NUM = -1L ^ (-1L << DATACENTER_BIT);
    private final static long MAX_MACHINE_NUM = -1L ^ (-1L << MACHINE_BIT);
    private final static long MAX_SEQUENCE = -1L ^ (-1L << SEQUENCE_BIT);

    // 每一部分向左的位移
    private final static long MACHINE_LEFT = SEQUENCE_BIT;
    private final static long DATACENTER_LEFT = SEQUENCE_BIT + MACHINE_BIT;
    private final static long TIMESTAMP_LEFT = DATACENTER_LEFT + DATACENTER_BIT;

    private long datacenterId;    // 数据中心ID
    private long machineId;       // 机器标识ID
    private long sequence = 0L;   // 序列号
    private long lastTimestamp = -1L; // 上一次时间戳

    /**
     * 构造函数（使用自动生成的机器ID和数据中心ID）
     */
    public IdWorkUtil() {
        this.datacenterId = getDatacenterId();
        this.machineId = getMaxMachineId(datacenterId);
    }

    /**
     * 构造函数（指定机器ID和数据中心ID）
     * @param datacenterId 数据中心ID (0~31)
     * @param machineId    机器ID (0~31)
     */
    public IdWorkUtil(long datacenterId, long machineId) {
        if (datacenterId > MAX_DATACENTER_NUM || datacenterId < 0) {
            throw new IllegalArgumentException("Datacenter ID can't be greater than " + MAX_DATACENTER_NUM + " or less than 0");
        }
        if (machineId > MAX_MACHINE_NUM || machineId < 0) {
            throw new IllegalArgumentException("Machine ID can't be greater than " + MAX_MACHINE_NUM + " or less than 0");
        }
        this.datacenterId = datacenterId;
        this.machineId = machineId;
    }

    /**
     * 生成下一个ID 18位数字
     * @return 雪花算法ID
     */
    public synchronized long nextId() {
        long currTimestamp = getNewTimestamp();

        if (currTimestamp < lastTimestamp) {
            // 时钟回拨处理
            long offset = lastTimestamp - currTimestamp;
            if (offset <= 5) {
                try {
                    // 等待时钟追上来
                    wait(offset << 1);
                    currTimestamp = getNewTimestamp();
                    if (currTimestamp < lastTimestamp) {
                        throw new RuntimeException("Clock moved backwards. Refusing to generate id");
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            } else {
                throw new RuntimeException("Clock moved backwards. Refusing to generate id");
            }
        }

        if (currTimestamp == lastTimestamp) {
            // 相同毫秒内，序列号自增
            sequence = (sequence + 1) & MAX_SEQUENCE;
            // 同一毫秒的序列数已经达到最大
            if (sequence == 0L) {
                currTimestamp = getNextMill();
            }
        } else {
            // 不同毫秒内，序列号置为0
            sequence = 0L;
        }

        lastTimestamp = currTimestamp;

        return (currTimestamp - START_TIMESTAMP) << TIMESTAMP_LEFT // 时间戳部分
                | datacenterId << DATACENTER_LEFT                  // 数据中心部分
                | machineId << MACHINE_LEFT                        // 机器标识部分
                | sequence;                                        // 序列号部分
    }

    /**
     * 获取下一毫秒
     */
    private long getNextMill() {
        long mill = getNewTimestamp();
        while (mill <= lastTimestamp) {
            mill = getNewTimestamp();
        }
        return mill;
    }

    /**
     * 获取当前时间戳
     */
    private long getNewTimestamp() {
        return System.currentTimeMillis();
    }

    /**
     * 获取最大机器ID
     */
    protected static long getMaxMachineId(long datacenterId) {
        // 根据MAC地址和进程ID生成机器ID
        try {
            String mac = getMac();
            int pid = getPid();
            int hash = mac.hashCode();
            // 确保生成的机器ID在有效范围内
            return (hash & 0xFFFF) % (MAX_MACHINE_NUM + 1);
        } catch (Exception e) {
            // 如果获取失败，使用随机值
            return (long) (Math.random() * (MAX_MACHINE_NUM + 1));
        }
    }

    /**
     * 获取数据中心ID
     */
    protected static long getDatacenterId() {
        // 根据本机IP地址生成数据中心ID
        try {
            InetAddress ip = InetAddress.getLocalHost();
            byte[] address = ip.getAddress();
            long id = ((address[address.length - 2] & 0xFF) << 8)
                    | (address[address.length - 1] & 0xFF);
            return id % (MAX_DATACENTER_NUM + 1);
        } catch (Exception e) {
            // 如果获取失败，使用默认值
            return 1L;
        }
    }

    /**
     * 获取本机MAC地址
     */
    private static String getMac() throws Exception {
        InetAddress ip = InetAddress.getLocalHost();
        NetworkInterface network = NetworkInterface.getByInetAddress(ip);
        byte[] mac = network.getHardwareAddress();

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < mac.length; i++) {
            sb.append(String.format("%02X", mac[i]));
            if (i < mac.length - 1) {
                sb.append(":");
            }
        }
        return sb.toString();
    }

    /**
     * 获取当前进程ID
     */
    private static int getPid() {
        String name = ManagementFactory.getRuntimeMXBean().getName();
        return Integer.parseInt(name.split("@")[0]);
    }

    /**
     * 解析ID
     * @param id 雪花算法ID
     * @return 包含时间戳、数据中心ID、机器ID和序列号的数组
     */
    public long[] parseId(long id) {
        long timestamp = (id >> TIMESTAMP_LEFT) + START_TIMESTAMP;
        long datacenterId = (id >> DATACENTER_LEFT) & MAX_DATACENTER_NUM;
        long machineId = (id >> MACHINE_LEFT) & MAX_MACHINE_NUM;
        long sequence = id & MAX_SEQUENCE;

        return new long[]{timestamp, datacenterId, machineId, sequence};
    }

    public static void main(String[] args) {
        IdWorkUtil workUtil = new IdWorkUtil();
        long nextId = workUtil.nextId();
        System.out.println(nextId);
    }
}
